/**
 * Copyright (c) 2012 Nokia Corporation.
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

import QtQuick 1.1
import com.nokia.meego 1.0
import QtMobility.location 1.2
import SocialConnectPlugin 1.0
import "CommonFunctions.js" as Functions


PageStackWindow {
    id: main

    property bool listViewVisible: false
    property Coordinate lastUpdatePos: Coordinate {}
    property bool logoutOnExit: false
    property alias map: placesMapPage.placesMap

    signal readyToBeShown()

    showStatusBar: true
    showToolBar: true
    initialPage: PlacesMapPage { id: placesMapPage; tools: mainToolBarLayout }

    Connections {
        target: placesListModel
        onError: Functions.requestFailed(requestId, errorString);
    }

    Connections {
        target: routeManager
        onRequestFailed: Functions.requestFailed(error);
    }

    /*!
      Process login completed.
     */
    function loginCompleted() {
        positionSource.active = true;
    }

    // A dialog to be shown if an error occurs.
    QueryDialog {
        id: errorDialog
        titleText: qsTr("Error");
        acceptButtonText: qsTr("Ok");
    }

    // Construct the Facebook Connect plug-in instance.
    FacebookConnect {
        id: fbConnect

        appId: "258008130941043"
        appName: "PlacesAround"
        organization: "Nokia"

        Component.onCompleted: {
            // Connect the signals.
            accessTokenChanged.connect(main.loginCompleted);
            requestCompleted.connect(Functions.requestCompleted)
            requestFailed.connect(Functions.requestFailed);
            permissions = ["publish_stream"];

            if (!isAuthorized()) {
                console.debug("Not authorized!");
                initTimer.start();
            }
            else {
                console.debug("Already authorized.");
                loginCompleted();
                initTimer.openLoginPage = false;
                initTimer.start();
            }
        }
    }

    // Timer for emitting readyToBeShown() signal and pushing the login page to
    // the page stack if necessary. The latter ensures that the login page is
    // pushed on top of the map page.
    Timer {
        id: initTimer
        property bool openLoginPage: true
        interval: 2000
        repeat: false
        running: false

        onTriggered: {
            if (openLoginPage) {
                console.debug("Opening the login page.")
                pageStack.push("qrc:/LoginPage.qml");
            }

            main.readyToBeShown();
        }
    }

    PositionSource {
        id: positionSource
        updateInterval: 5000
        active: false
        property bool initialized: false

        onPositionChanged: {
            if (!initialized) {
                Functions.checkForUpdate(true);
                map.updateCoordinates(position.coordinate);
                map.positionSourceInitialized();
                initialized = true;
            }
            else {
                var accuracyInMeters = Math.max(position.horizontalAccuracy,
                                                position.verticalAccuracy);
                map.moveHereToCoordinate(position.coordinate, accuracyInMeters);
            }

            Functions.checkForUpdate(false);
            settings.setSetting("last_latitude", position.coordinate.latitude);
            settings.setSetting("last_longitude", position.coordinate.longitude);
        }
    }

    // Bar containing a text filter for entering text for filtering the found
    // places.
    FilterBar {
        id: filterBar

        anchors {
            top: parent.top
            margins: 35
        }
    }

    Loader {
        id: splashScreenLoader

        /*!
          Deletes the splash screen.
        */
        function deleteSplashScreen()
        {
            splashScreenLoader.source = "";
        }

        anchors.fill: parent
        source: Qt.resolvedUrl("qrc:/SplashScreen.qml");

        onLoaded: {
            item.text = "Loading...";
            item.hidden.connect(splashScreenLoader.deleteSplashScreen);
            main.readyToBeShown.connect(splashScreenLoader.item.hide);
        }
    }

    // View menu for opening settings and info page.
    Menu {
        id: viewMenu
        visualParent: pageStack

        MenuLayout {
            MenuItem {
                text: qsTr("Settings");

                onClicked: {
                    filterBar.hide();
                    pageStack.push("qrc:/SettingsPage.qml");
                }
            }
            MenuItem {
                text: qsTr("About");

                onClicked: {
                    filterBar.hide();
                    pageStack.push("qrc:/InfoPage.qml");
                }
            }
        }
    }

    ToolBarLayout {
        id: mainToolBarLayout

        ToolIcon {
            id: searchButton
            property bool checked: false
            onCheckedChanged: checked ? filterBar.state = "shown"
                                      : filterBar.state = "hidden";
            iconId: "toolbar-search"
            onClicked: checked = !checked;
        }
        ButtonRow {
            id: buttonRow
            property bool mapSelected: true
            checkedButton: mapViewButton

            Button {
                id: mapViewButton
                checked: true
                iconSource: checked ? "qrc:/map-icon.png" : "qrc:/map-icon-inv.png";

                onClicked: {
                    if (!buttonRow.mapSelected) {
                        Functions.showMap();
                    }
                }
            }
            Button {
                id: listViewButton
                iconSource: checked ? "qrc:/list-icon.png" : "qrc:/list-icon-inv.png";

                onClicked: {
                    if (buttonRow.mapSelected) {
                        pageStack.push("qrc:/PlacesListPage.qml", { tools: mainToolBarLayout });
                        buttonRow.mapSelected = false;
                        listViewVisible = true;
                    }
                }
            }
        }
        ToolIcon {
            iconId: "toolbar-view-menu"
            onClicked: viewMenu.open();
        }
    }

    Component.onCompleted: {
        // Get the "logout on exit" setting
        var logoutOnExitSetting = settings.getSetting("logoutOnExit");
        console.debug("\"logoutOnExit\" setting set to " + logoutOnExitSetting);

        if (logoutOnExitSetting == undefined) {
            // Store the setting for the first time
            settings.setSetting("logoutOnExit", false);
        }
        else if (logoutOnExitSetting == "true") {
            logoutOnExit = true;
        }
    }
    Component.onDestruction: {
        if (logoutOnExit) {
            console.debug("Logging out.");
            fbConnect.logout();
        }
    }
}
